﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Rehabilitation.Models;

namespace Rehabilitation.Controllers
{
    public class PatientsController : Controller
    {
        private DBEntities db = new DBEntities();

        public static int recordsPerPage = 20;

        protected override void Initialize(System.Web.Routing.RequestContext requestContext)
        {
            base.Initialize(requestContext);

            if (!Request.IsAuthenticated || Session["User"] == null)
            {
                Response.Redirect("/Account/LogOff");
            }
        }


        //
        // GET: /Patients/

        public ActionResult Index()
        {
            ViewBag.OrderBy = "id";
            ViewBag.SortOrder = "a";
            List<string> orders = new List<string>(){"firstName", "lastName", "id","dateOfBirth", "sex"};
            string orderByStr = Request.Params["orderBy"];
            string sortOrderStr = Request.Params["sortOrder"];
            string pageStr = Request.Params["page"];
            string searchDate = Request.Params["DateOfBirth"];
            ViewBag.DateOfBirth = searchDate;
            string searchName = Request.Params["Name"];
            ViewBag.Name = searchName;
            int page = 1;
            if(!string.IsNullOrEmpty(pageStr))
            {
                try
                {
                    page = int.Parse(pageStr);
                }finally
                {
                    if (page < 1) page = 1;
                }
            }
            List<Patient> result = db.Patients.ToList();
            if(!string.IsNullOrEmpty(searchDate))
            {
                try
                {
                    DateTime dob = DateTime.Parse(searchDate);
                    result = result.Where(p => p.DateOfBirth.Equals(dob)).ToList();
                }finally
                {
                    
                }
            }
            if(!string.IsNullOrEmpty(searchName))
            {
                if(searchName.Contains(","))
                {
                    string lastname = searchName.Substring(0, searchName.IndexOf(",")).Trim();
                    string firstname = searchName.Substring(searchName.IndexOf(",") + 1).Trim();
                    result =
                        result.Where(
                            p =>
                            string.IsNullOrEmpty(lastname)
                                ? true
                                : p.LastName.ToLower().Contains(lastname.ToLower()) && string.IsNullOrEmpty(firstname)
                                      ? true
                                      : p.FirstName.ToLower().Contains(firstname.ToLower())).ToList();
                }else if(searchName.Contains(" "))
                {
                    string firstname = searchName.Substring(0, searchName.IndexOf(" ")).Trim();
                    string lastname = searchName.Substring(searchName.IndexOf(" ") + 1).Trim();
                    result =
                        result.Where(
                            p =>
                            string.IsNullOrEmpty(lastname)
                                ? true
                                : p.LastName.ToLower().Contains(lastname.ToLower()) && string.IsNullOrEmpty(firstname)
                                      ? true
                                      : p.FirstName.ToLower().Contains(firstname.ToLower())).ToList();
                }else
                {
                    result.Where(
                        p =>
                        p.FirstName.ToLower().Contains(searchName.ToLower()) ||
                        p.LastName.ToLower().Contains(searchName.ToLower())).ToList();
                }
            }
            if(!string.IsNullOrEmpty(orderByStr) && orders.Contains(orderByStr))
            {
                if(!string.IsNullOrEmpty(sortOrderStr) && sortOrderStr.Equals("d"))
                {
                    ViewBag.SortOrder = "d";
                    switch (orderByStr)
                    {
                        case "firstName":
                            result = result.OrderByDescending(p => p.FirstName).ToList();
                            ViewBag.OrderBy = "firstName";
                            break;
                        case "lastName":
                            result = result.OrderByDescending(p => p.LastName).ToList();
                            ViewBag.OrderBy = "lastName";
                            break;
                        case "id":
                            result = result.OrderByDescending(p => p.PatientID).ToList();
                            ViewBag.OrderBy = "id";
                            break;
                        case "dateOfBirth":
                            result = result.OrderByDescending(p => p.DateOfBirth).ToList();
                            ViewBag.OrderBy = "dateOfBirth";
                            break;
                        case "sex":
                            result = result.OrderByDescending(p => p.Sex).ToList();
                            ViewBag.OrderBy = "sex";
                            break;
                        default:
                            break;
                    }
                }else
                {
                    switch (orderByStr)
                    {
                        case "firstName":
                            result = result.OrderBy(p => p.FirstName).ToList();
                            ViewBag.OrderBy = "firstName";
                            break;
                        case "lastName":
                            result = result.OrderBy(p => p.LastName).ToList();
                            ViewBag.OrderBy = "lastName";
                            break;
                        case "id":
                            result = result.OrderBy(p => p.PatientID).ToList();
                            ViewBag.OrderBy = "id";
                            break;
                        case "dateOfBirth":
                            result = result.OrderBy(p => p.DateOfBirth).ToList();
                            ViewBag.OrderBy = "dateOfBirth";
                            break;
                        case "sex":
                            result = result.OrderBy(p => p.Sex).ToList();
                            ViewBag.OrderBy = "sex";
                            break;
                        default:
                            break;
                    }
                }
                
            }
            ViewBag.NumberOfPages = result.Count/recordsPerPage + (result.Count%recordsPerPage > 0 ? 1 : 0);
            result = result.Skip(recordsPerPage*(page - 1)).Take(recordsPerPage).ToList();
            return View(result);
        }

        //
        // GET: /Patients/Details/5

        public ActionResult Details(long id = 0)
        {
            Patient patient = db.Patients.Single(p => p.PatientID == id);
            if (patient == null)
            {
                return HttpNotFound();
            }
            ViewBag.Patient = patient;
            ViewBag.Tests = (from t in db.Tests where t.PatientID == patient.PatientID select t).ToList();
            return View(patient);
        }

        //
        // GET: /Patients/Create

        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Patients/Create

        [HttpPost]
        public ActionResult Create(Patient patient)
        {
            if (ModelState.IsValid)
            {
                db.Patients.AddObject(patient);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(patient);
        }

        //
        // GET: /Patients/Edit/5

        public ActionResult Edit(long id = 0)
        {
            Patient patient = db.Patients.Single(p => p.PatientID == id);
            if (patient == null)
            {
                return HttpNotFound();
            }
            return View(patient);
        }

        //
        // POST: /Patients/Edit/5

        [HttpPost]
        public ActionResult Edit(Patient patient)
        {
            if (ModelState.IsValid)
            {
                db.Patients.Attach(patient);
                db.ObjectStateManager.ChangeObjectState(patient, EntityState.Modified);
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(patient);
        }

        //
        // GET: /Patients/Delete/5

        public ActionResult Delete(long id = 0)
        {
            Patient patient = db.Patients.Single(p => p.PatientID == id);
            if (patient == null)
            {
                return HttpNotFound();
            }
            return View(patient);
        }

        //
        // POST: /Patients/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(long id)
        {
            Patient patient = db.Patients.Single(p => p.PatientID == id);
            db.Patients.DeleteObject(patient);
            db.SaveChanges();
            return RedirectToAction("Index");
        }




        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}